//
// Copyright (c) Microsoft Corporation.  All rights reserved.
//
//
// Use of this sample source code is subject to the terms of the Microsoft
// license agreement under which you licensed this sample source code. If
// you did not accept the terms of the license agreement, you are not
// authorized to use this sample source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the LICENSE.RTF on your install media or the root of your tools installation.
// THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
//
//////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2003 Intrinsyc Europe Ltd.
//////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2004 Siemens AG
//
// Version: 1.1.2.5
// Date:    11. Jan. 2006
//////////////////////////////////////////////////////////////////////////////


#include "precomp.h"

//
// Convert a RILMSGDCS struct into a TP-DCS BYTE for Submit messages
// see GSM 03.38
//
static HRESULT EncodeMsgDCS(const RILMSGDCS& rmdDCS, BYTE* const pbOut, UINT& rcbUsed)
{
    TBD_FUNCTION(EncodeMsgDCS);
    TBD_ASSERT(NULL != pbOut);

    HRESULT hr = S_OK;

    rcbUsed = 0;

    if (!(rmdDCS.dwParams & RIL_PARAM_MDCS_TYPE)) {
        hr = E_INVALIDARG;
        goto Error;
    }
    *pbOut = 0x00;

    switch (rmdDCS.dwType)
    {
        case RIL_DCSTYPE_GENERAL:
            if ((rmdDCS.dwParams & RIL_PARAM_MDCS_FLAGS) &&
                (rmdDCS.dwFlags & RIL_DCSFLAG_COMPRESSED)) {
                *pbOut |= 0x20;
            }

            if (rmdDCS.dwParams & RIL_PARAM_MDCS_MSGCLASS) {
                switch (rmdDCS.dwMsgClass)
                {
                    case RIL_DCSMSGCLASS_0:
                        *pbOut |= 0x10;
                        break;

                    case RIL_DCSMSGCLASS_1:
                        *pbOut |= 0x11;
                        break;

                    case RIL_DCSMSGCLASS_2:
                        *pbOut |= 0x12;
                        break;

                    case RIL_DCSMSGCLASS_3:
                        *pbOut |= 0x13;
                        break;

                    default:
                        hr = E_INVALIDARG;
                        goto Error;
                }
            }

            if (rmdDCS.dwParams & RIL_PARAM_MDCS_ALPHABET) {
                switch (rmdDCS.dwAlphabet)
                {
                    case RIL_DCSALPHABET_DEFAULT:
                        *pbOut |= 0x00;
                        break;

                    case RIL_DCSALPHABET_8BIT:
                        *pbOut |= 0x04;
                        break;

                    case RIL_DCSALPHABET_UCS2:
                        *pbOut |= 0x08;
                        break;

                    default:
                        hr = E_INVALIDARG;
                        goto Error;
                }
            } else {
                hr = E_INVALIDARG;
                goto Error;
            }
            break;

        case RIL_DCSTYPE_MSGWAIT:
            if (!(rmdDCS.dwParams & RIL_PARAM_MDCS_FLAGS)) {
                hr = E_INVALIDARG;
                goto Error;
            }

            if (rmdDCS.dwFlags & RIL_DCSFLAG_DISCARD) {
                *pbOut |= 0xc0;
            } else if (rmdDCS.dwParams & RIL_PARAM_MDCS_ALPHABET) {
                switch (rmdDCS.dwAlphabet)
                {
                    case RIL_DCSALPHABET_DEFAULT:
                        *pbOut |= 0xd0;
                        break;

                    case RIL_DCSALPHABET_UCS2:
                        *pbOut |= 0xe0;
                        break;

                    default:
                        hr = E_INVALIDARG;
                        goto Error;
                }
            } else {
                hr = E_INVALIDARG;
                goto Error;
            }

            if (rmdDCS.dwParams & RIL_PARAM_MDCS_INDICATION &&
                rmdDCS.dwFlags & RIL_DCSFLAG_INDICATIONACTIVE) {
                switch (rmdDCS.dwIndication)
                {
                    case RIL_DCSINDICATION_VOICEMAIL:
                        *pbOut |= 0x08;
                        break;

                    case RIL_DCSINDICATION_FAX:
                        *pbOut |= 0x09;
                        break;

                    case RIL_DCSINDICATION_EMAIL:
                        *pbOut |= 0x0a;
                        break;

                    default:
                        hr = E_INVALIDARG;
                        goto Error;
                }
            }
            break;

        case RIL_DCSTYPE_MSGCLASS:
            // This type is currently not implemented
            hr = E_INVALIDARG;
            goto Error;

        default:
            hr = E_FAIL;
            goto Error;
    }
    rcbUsed = 1;

Error:
    return hr;
}


//
// Encode the Service Center Time Stamp in a SYSTEMTIME struct
// see 9.2.3.11
//
static void EncodeMsgTimeStamp(const SYSTEMTIME& stTimeStamp, BYTE* const pbOut, UINT& rcbUsed)
{
    TBD_FUNCTION(EncodeMsgTimeStamp);
    TBD_ASSERT(NULL != pbOut);

    BYTE* pbWalk = pbOut;

    rcbUsed = 0;

    *pbWalk++ = ((stTimeStamp.wYear % 10) << 4)   | ((stTimeStamp.wYear / 10) % 10);
    *pbWalk++ = ((stTimeStamp.wMonth % 10) << 4)  | (stTimeStamp.wMonth / 10);
    *pbWalk++ = ((stTimeStamp.wDay % 10) << 4)    | (stTimeStamp.wDay / 10);
    *pbWalk++ = ((stTimeStamp.wHour % 10) << 4)   | (stTimeStamp.wHour / 10);
    *pbWalk++ = ((stTimeStamp.wMinute % 10) << 4) | (stTimeStamp.wMinute / 10);
    *pbWalk++ = ((stTimeStamp.wSecond % 10) << 4) | (stTimeStamp.wSecond / 10);
    *pbWalk++ = 0;      // Set time zone to UTC

    rcbUsed = pbWalk - pbOut;
}

//
//
//
// GSM 3.40, Section 9.2.3.12.1
//
// TP-VP Value  Validity period value                       Range
// ----------------------------------
//  0   - 143   (TP-VP + 1) x 5 minutes                     5 mins - 720 mins (.5 day)
//  144 - 167   12 hours + ((TP-VP - 143) x 30 minutes)     750 mins - 1440 mins (1 day)
//  168 - 196   (TP-VP - 166) x 1 day                       2 days -  30 days (43200 mins)
//  197 - 255   (TP-VP - 192) x 1 week                      35 days - 441 days (635040 mins)
//
//
// This function encodes a SYSTEMTIME structure into a TP-VP Value according to the chart above.
// Only a subset of the SYSTEMTIME structure is used: wDay, wHour, wMinute. These are the only
// units that have a consistent conversion, and values greater than 441 days are not used, so
// these members are sufficient for expressing any supported validity period.
//
// If the expressed system time does not fall exactly onto a validity period increment, then
// the period is rounded up to the next increment.
//
static void EncodeRelativeValidityPeriod(const SYSTEMTIME& stVP, BYTE* const pbOut, UINT& rcbUsed)
{
    UINT uMinutes = 0;

    uMinutes = stVP.wMinute + 60 * (stVP.wHour + 24 * stVP.wDay);

    if (0 == uMinutes)
    {
        *pbOut = 0;
    }
    else if (uMinutes <= 720)
    {
        *pbOut = (BYTE)((uMinutes+4) / 5) - 1;
    }
    else if (uMinutes <= 1440)
    {
        *pbOut = (BYTE)((uMinutes+29) / 30) + 119;
    }
    else if (uMinutes <= 43200)
    {
        *pbOut = (BYTE)((uMinutes+1439) / 1440) + 166;
    }
    else if (uMinutes <= 635040)
    {
        *pbOut = (BYTE)((uMinutes+10079) / 10080) + 192;
    }
    else
    {
        *pbOut = 255;
    }

    rcbUsed = 1;
}

//
// Convert a VP time stamp to BYTE data
// see GSM 03.40 section 9.2.3.12
//
static HRESULT EncodeMsgValidityPeriod(const SYSTEMTIME& stVP, const DWORD dwVPFormat, BYTE* const pbOut, UINT& rcbUsed)
{
    TBD_FUNCTION(EncodeMsgValidityPeriod);
    TBD_ASSERT(NULL != pbOut);

    HRESULT hr = S_OK;
    BYTE* pbWalk = pbOut;

    rcbUsed = 0;

    if (RIL_MSGVP_ABSOLUTE == dwVPFormat) {
        EncodeMsgTimeStamp(stVP, pbOut, rcbUsed);
    } else {
        switch (dwVPFormat)
        {
            case RIL_MSGVP_NONE:
                // Do nothing
                break;

            case RIL_MSGVP_ENHANCED:
                // Enhanced isn't supported. We should never get here,
                // but just in case, treat the SYSTEMTIME as relative.

            case RIL_MSGVP_RELATIVE:
                EncodeRelativeValidityPeriod(stVP, pbOut, rcbUsed);
                break;

            default:
                hr = E_INVALIDARG;
                goto Error;
        }
    }

Error:
    return hr;
}



//
// Function to encode an address from an RILADDRESS struct
// see GSM 03.40 section 9.1.2.5
//
static HRESULT EncodeMsgAddress(const RILADDRESS& raAddress, const BOOL fBeforePDU, BYTE* const pbOut, UINT& rcbUsed)
{
    TBD_FUNCTION(EncodeMsgAddress);
    TBD_ASSERT(NULL != pbOut);

    HRESULT hr = S_OK;
    UINT j;
    UINT cchAddressLen;
    BYTE bTypeOfAddress;
    UINT nTemp;
    WCHAR wszRILAddress[MAXLENGTH_ADDRESS + 1];
    LPWSTR wszRILAddressWalk;
    char szAddress[MAXLENGTH_ADDRESS + 1];
    WCHAR wszBuffer[2];
    BYTE* pbWalk = pbOut;

    rcbUsed = 0;

    if (!(raAddress.dwParams & RIL_PARAM_A_ADDRESS) ||
        !(raAddress.dwParams & RIL_PARAM_A_TYPE)) {
        // Address and type must be specified
        hr = E_INVALIDARG;
        goto Error;
    }

    if (NUM_ADDRTYPES <= raAddress.dwType) {
        // Incorrect type specified
        hr = E_INVALIDARG;
        goto Error;
    }

    // Set address type, top bit is always set
    bTypeOfAddress = 0x80 | (g_rgbAddrTypes[raAddress.dwType] << 4);

    // Set numplan type, if necessary
    if (RIL_ADDRTYPE_UNKNOWN == raAddress.dwType ||
        RIL_ADDRTYPE_INTERNATIONAL == raAddress.dwType ||
        RIL_ADDRTYPE_NATIONAL == raAddress.dwType) {

        if (!(raAddress.dwParams & RIL_PARAM_A_NUMPLAN) ||
            NUM_NUMPLANS <= raAddress.dwNumPlan) {
            hr = E_INVALIDARG;
            goto Error;
        }

        bTypeOfAddress |= g_rgbNumPlans[raAddress.dwNumPlan];
    }

    // Copy the address, removing all unwanted characters (Ex: '(', '-', '.')
    // Note that '+' is automatically removed from INTERNATIONAL addresses
    wszRILAddressWalk = wszRILAddress;
    C_ASSERT(ARRAY_LENGTH(raAddress.wszAddress) < ARRAY_LENGTH(wszRILAddress));
    for(j = 0 ; j < ARRAY_LENGTH(raAddress.wszAddress) ; j++) {
        if(strchr("1234567890*#ABCD", raAddress.wszAddress[j])) {
            *wszRILAddressWalk++ = raAddress.wszAddress[j];
        } else if(L'\0' == raAddress.wszAddress[j]) {
            break;  // Done
        }
    }
    *wszRILAddressWalk = L'\0';

    // Note: Untested for ALPHANUM addresses
    cchAddressLen = wcslen(wszRILAddress);
    if (fBeforePDU) {
        *pbWalk++ = ((cchAddressLen + 1)/ 2) + 1;
    } else {
        *pbWalk++ = cchAddressLen;
    }

    *pbWalk++ = bTypeOfAddress;

    if (RIL_ADDRTYPE_ALPHANUM == raAddress.dwType) {
        hr = RILAddressToString(raAddress, szAddress, MAXLENGTH_ADDRESS + 1, bTypeOfAddress);
        if (FAILED(hr)) {
            goto Error;
        }
        TBD_ASSERT(strlen(szAddress) <= MAXLENGTH_ADDRESS);
        memcpy(pbWalk, szAddress, strlen(szAddress));
    } else {
        wszBuffer[1] = L'\0';  // Not changed below
        for (j = 0; j < cchAddressLen; j += 2) {
            wszBuffer[0] = wszRILAddress[j];
            nTemp = _wtoi(wszBuffer);
            *pbWalk = nTemp;

            if (j + 1 < cchAddressLen) {
                wszBuffer[0] = wszRILAddress[j + 1];
                nTemp = _wtoi(wszBuffer);
                *pbWalk++ |= nTemp << 4;
            } else {
                *pbWalk++ |= 0xf0;
            }
        }
    }
    rcbUsed = pbWalk - pbOut;

Error:
    return hr;
}


//
// Encode the ProtocolID for an outgoing message
// see GSM 03.40 section 9.2.3.9
//
static HRESULT EncodeMsgProtocolID(const DWORD dwProtocolID, BYTE* const pbOut, UINT& rcbUsed)
{
    TBD_FUNCTION(EncodeMsgProtocolID);
    TBD_ASSERT(NULL != pbOut);

    HRESULT hr = S_OK;

    rcbUsed = 0;

    if (dwProtocolID > NUM_PROTOCOLIDS) {
        hr = E_INVALIDARG;
        goto Error;
    }

    if (dwProtocolID == RIL_MSGPROTOCOL_SMETOSME) {
        *pbOut = 0x00;
    } else {
        TBD_ASSERT(0x100 > g_rgdwProtocolIDs[dwProtocolID]);
        *pbOut = (BYTE)g_rgdwProtocolIDs[dwProtocolID];
    }
    rcbUsed = 1;

Error:
    return hr;
}


//
// calculate the total length of the user data in an outgoing message
// if fGSMDefault is trure, then the length is measured in septets, otherwise in octets
//
static void EncodeEncDataLength(const DWORD cchMsgLength, const DWORD cbHdrLength, const DWORD dwAlphabet, BYTE* const pbOut,
                                UINT& rcbUsed)
{
    TBD_FUNCTION(EncodeEncDataLength);
    TBD_ASSERT(NULL != pbOut);

    UINT cchUserData;

    rcbUsed = 0;

    if (!cchMsgLength && !cbHdrLength) {
        // Neither header nor body are specified
        cchUserData = 0;
    } else {
        if (RIL_DCSALPHABET_UCS2 == dwAlphabet) {
            // Account for the fact that every UCS2 char takes up 2 bytes
            cchUserData = cchMsgLength * 2;
        } else {
            cchUserData = cchMsgLength;
        }

        if (cbHdrLength) {
            // Add the size of the header, and a byte for the header-length indicator, plus any fill-bits
            //    (for GSM default alpabet)

            if (RIL_DCSALPHABET_DEFAULT == dwAlphabet) {
                cchUserData += (DIVIDE_ROUNDING_UP((1 + cbHdrLength) * 8, 7));
            } else {
                cchUserData += (1 + cbHdrLength);
            }
        }
    }

    *pbOut = cchUserData;
    rcbUsed = 1;
}


//
// Fill out a BYTE array for the header of an outgoing message
//
static void EncodeMsgHdr(const BYTE* const pbIn, const cbHdrLength, const DWORD dwAlphabet, BYTE* const pbOut, UINT& rcbUsed)
{
    TBD_FUNCTION(EncodeMsgHdr);
    TBD_ASSERT(NULL != pbIn);
    TBD_ASSERT(NULL != pbOut);

    BYTE* pbWalk = pbOut;

    rcbUsed = 0;

    if (cbHdrLength) {
        *pbWalk++ = cbHdrLength;

        memcpy(pbWalk, pbIn, min(cbHdrLength, MAXLENGTH_ADDRESS));
        pbWalk += cbHdrLength;
    }
    rcbUsed = pbWalk - pbOut;
}


//
//
//
static HRESULT EncodeMsgDlvStatus(const DWORD dwStatus, BYTE* const pbOut, UINT& rcbUsed)
{
    TBD_FUNCTION(EncodeMsgDlvStatus);
    TBD_ASSERT(NULL != pbOut);

    HRESULT hr = S_OK;

    rcbUsed = 0;

    if (NUM_DLVSTATUS <= dwStatus) {
        hr = E_INVALIDARG;
        goto Error;
    }

    *pbOut = (BYTE) g_rgdwDlvStatus[dwStatus];
    rcbUsed = 1;

Error:
    return hr;
}

void ShiftPackedBufferNBitsLeft(BYTE *pbyBuffer, DWORD cBufferBytes, DWORD cShiftRightBits)
{
    if (0 != cBufferBytes)
    {
        BYTE *pbyCurrentByte = pbyBuffer + cBufferBytes - 1;
        while (pbyCurrentByte > pbyBuffer )
        {
            *pbyCurrentByte-- = ((*pbyCurrentByte << cShiftRightBits) |
                                 (*(pbyCurrentByte - 1) >> (8 - cShiftRightBits)));
        }
        *pbyCurrentByte = (*pbyCurrentByte << cShiftRightBits);
    }
}

//
//
//
static void EncodeMsgHeaderAndBody(const DWORD dwParams, const DWORD dwFlags, const DWORD cchMsgLength, const DWORD cbHdrLength,
                                   const BYTE* const pbHdr, const BYTE* const pbMsg, const RILMSGDCS* const prmdDataCoding,
                                   BYTE* const pbOut, UINT& rcbUsed)
{
    TBD_FUNCTION(EncodeMsgHeaderAndBody);
    TBD_ASSERT(NULL != pbOut);

    BYTE* pbWalk = pbOut;
    DWORD dwAlphabet;
    UINT cbMsgBytes;
    UINT cbAdvancedBy;
    DWORD dwBitsToShift = 0;
//  DWORD i;

    rcbUsed = 0;

    if (!(dwFlags & RIL_MSGFLAG_HEADER) && !cchMsgLength) {
        // There is no header or data for this message, so set the data length to zero,
        //    and skip the rest of the function
        *pbWalk++ = 0;
    } else {
        if (prmdDataCoding && (prmdDataCoding->dwParams & RIL_PARAM_MDCS_ALPHABET)) {
            dwAlphabet = prmdDataCoding->dwAlphabet;
        } else {
            // Default to 8-bit alphabet
            dwAlphabet = RIL_DCSALPHABET_8BIT;
        }

        // Calculate the length of the user data in the message
        EncodeEncDataLength(cchMsgLength, (dwFlags & RIL_MSGFLAG_HEADER) ? cbHdrLength : 0, dwAlphabet, pbWalk, cbAdvancedBy);
        pbWalk += cbAdvancedBy;

        // Set the header, if it exists
        if ((dwParams & RIL_PARAM_M_HDRLENGTH) && (dwParams & RIL_PARAM_M_HDR)) {
            // Encode message header
            EncodeMsgHdr(pbHdr, cbHdrLength, dwAlphabet, pbWalk, cbAdvancedBy);
            pbWalk += cbAdvancedBy;
            if (RIL_DCSALPHABET_DEFAULT == dwAlphabet) {
                dwBitsToShift = 7-((cbAdvancedBy * 8) % 7);
                if (dwBitsToShift == 7) dwBitsToShift = 0;
            }
        }

        // Set the message data
        if (cchMsgLength) {
            // Figure out the number of bytes the body would occupy
            if (RIL_DCSALPHABET_DEFAULT == dwAlphabet) {
                cbMsgBytes = (cchMsgLength * 7 + 7) / 8;
            } else if (RIL_DCSALPHABET_UCS2 == dwAlphabet) {
                cbMsgBytes = cchMsgLength * 2;
            } else {
                cbMsgBytes = cchMsgLength;
            }

            cbAdvancedBy = min(cbMsgBytes, MAXLENGTH_MSG);
            memcpy(pbWalk, pbMsg, cbAdvancedBy);


            // make sure any GSM characters start on the septet boundry, not on the byte boundry.
            if (dwBitsToShift) {
                if (((cchMsgLength * 7 + 7 + dwBitsToShift) / 8) > cbMsgBytes)
                {
                    ASSERT(cbAdvancedBy < MAXLENGTH_MSG);
                    if(cbAdvancedBy < MAXLENGTH_MSG)
                    {
                        // our shift will overflow into the next byte
                        pbWalk[cbAdvancedBy++] = 0;
                    }
                }
                ShiftPackedBufferNBitsLeft(pbWalk, cbAdvancedBy, dwBitsToShift);
            }


            pbWalk += cbAdvancedBy;
        }
        else
        {
            // If there is no message body then we may need to walk one more byte to make it to snag
            // the next septet boundry.
            if (dwBitsToShift)
            {
                pbWalk++;
            }
        }
    }
    rcbUsed = pbWalk - pbOut;
}


//
// Fill out a BYTE array for a Submit message
//
static HRESULT EncodeSubmitMsg(const RILMESSAGE& rmMsg, BYTE* const pbOut, const UINT cbOut, UINT& rcbUsed)
{
    TBD_FUNCTION(EncodeSubmitMsg);
    TBD_ASSERT(NULL != pbOut);

    BYTE* pbWalk = pbOut;
    BYTE* pbEnd = pbOut + cbOut;
    UINT cbAdvancedBy;
    HRESULT hr = S_OK;

    (void)memset(pbOut, 0, cbOut);

    // These parameters are mandatory, and if not present, we error out
    if (!(rmMsg.dwParams & RIL_PARAM_M_TYPE) || !(rmMsg.dwParams & RIL_PARAM_M_DESTADDRESS) ||
        !(rmMsg.dwParams & RIL_PARAM_M_PROTOCOLID) || !(rmMsg.dwParams & RIL_PARAM_M_MSGLENGTH) ||
        !(rmMsg.dwParams & RIL_PARAM_M_FLAGS) || !(rmMsg.dwParams & RIL_PARAM_M_VPFORMAT) ||
        !(rmMsg.dwParams & RIL_PARAM_M_DATACODING)) {
        hr = E_INVALIDARG;
        goto Error;
    }

    // Set Type, per GSM 03.40 section 9.2.3.1
    *pbWalk |= 0x01;

    // RIL_MSGFLAGS_REJECTDUPS, GSM 03.40 section 9.2.3.25
    if (rmMsg.dwFlags & RIL_MSGFLAG_REJECTDUPS) {
        *pbWalk |= 0x04;
    }

    // Validity Period Format, GSM 03.40 section 9.2.3.3
    switch (rmMsg.msgOutSubmit.dwVPFormat)
    {
        case RIL_MSGVP_NONE:
            *pbWalk |= 0x00;
            break;

        case RIL_MSGVP_ENHANCED:
            //*pbWalk |= 0x08;
            ASSERT(FALSE);      // not supported, treat SYSTEMTIME as relative
            // fall through...

        case RIL_MSGVP_RELATIVE:
            *pbWalk |= 0x10;
            break;

        case RIL_MSGVP_ABSOLUTE:
            *pbWalk |= 0x18;
            break;

        default:
            hr = E_INVALIDARG;
            goto Error;
    }

    // RIL_MSGFLAG_STATUSREPORTREQUESTED, GSM 03.40 section 9.2.3.5
    if (rmMsg.dwFlags & RIL_MSGFLAG_STATUSREPORTREQUESTED) {
        *pbWalk |= 0x20;
    }

    // RIL_MSGFLAG_HEADER, GSM 03.40 section 9.2.3.23
    if (rmMsg.dwFlags & RIL_MSGFLAG_HEADER) {
        *pbWalk |= 0x40;
    }

    // RIL_MSGFLAG_REPLYPATH, GSM 03.40 section 9.2.3.17
    if (rmMsg.dwFlags & RIL_MSGFLAG_REPLYPATH) {
        *pbWalk |= 0x80;
    }

    pbWalk++;
    TBD_ASSERT(pbWalk <= pbEnd);

    // RIL_PARAM_M_MSGREFERENCE, GSM 03.40 section 9.2.3.6
    // NOTE: it appears that we can put anything into this field -- the radio generates correct msg reference for us
    pbWalk++;
    TBD_ASSERT(pbWalk <= pbEnd);

    // Encode the destination address.  pbWalk should be set properly by the function
    hr = EncodeMsgAddress(rmMsg.msgOutSubmit.raDestAddress, FALSE, pbWalk, cbAdvancedBy);
    if (FAILED(hr)) {
        goto Error;
    }
    pbWalk += cbAdvancedBy;
    TBD_ASSERT(pbWalk <= pbEnd);

    // Set ProtocolID, see GSM 03.40 section 9.2.3.9
    hr = EncodeMsgProtocolID(rmMsg.msgOutSubmit.dwProtocolID, pbWalk, cbAdvancedBy);
    if (FAILED(hr)) {
        goto Error;
    }
    pbWalk += cbAdvancedBy;
    TBD_ASSERT(pbWalk <= pbEnd);

    // Reconstruct DCS, see GSM 03.40 section 9.2.3.10
    hr = EncodeMsgDCS(rmMsg.msgOutSubmit.rmdDataCoding, pbWalk, cbAdvancedBy);
    if (FAILED(hr)) {
        goto Error;
    }
    pbWalk += cbAdvancedBy;
    TBD_ASSERT(pbWalk <= pbEnd);

    if (rmMsg.dwParams & RIL_PARAM_M_VP) {
        TBD_ASSERT(0 != (rmMsg.dwParams & RIL_PARAM_M_VPFORMAT));

        // See GSM 03.40 section 9.2.3.12
        hr = EncodeMsgValidityPeriod(rmMsg.msgOutSubmit.stVP, rmMsg.msgOutSubmit.dwVPFormat, pbWalk, cbAdvancedBy);
        if (FAILED(hr)) {
            goto Error;
        }
        pbWalk += cbAdvancedBy;
        TBD_ASSERT(pbWalk <= pbEnd);
    }

    // Encode header and body
    EncodeMsgHeaderAndBody(rmMsg.dwParams, rmMsg.dwFlags, rmMsg.msgOutSubmit.cchMsgLength,
                           rmMsg.msgOutSubmit.cbHdrLength, rmMsg.msgOutSubmit.rgbHdr, rmMsg.msgOutSubmit.rgbMsg,
                           &rmMsg.msgOutSubmit.rmdDataCoding, pbWalk, cbAdvancedBy);
    pbWalk += cbAdvancedBy;
    TBD_ASSERT(pbWalk <= pbEnd);

    rcbUsed = pbWalk - pbOut;

Error:
    return hr;
}


//
// Fill out a BYTE array for a Command message
//
static HRESULT EncodeCmdMsg(const RILMESSAGE& rmMsg, BYTE* const pbOut, const UINT cbOut, UINT& rcbUsed)
{
    TBD_FUNCTION(EncodeCmdMsg);
    TBD_ASSERT(NULL != pbOut);

    BYTE* pbWalk = pbOut;
    BYTE* pbEnd = pbOut + cbOut;
    UINT cbAdvancedBy;
    HRESULT hr = S_OK;

    (void)memset(pbOut, 0, cbOut);

    // These parameters are mandatory, and if not present, we error out.
    if (!(rmMsg.dwParams & RIL_PARAM_M_TYPE) || !(rmMsg.dwParams & RIL_PARAM_M_DESTADDRESS) ||
        !(rmMsg.dwParams & RIL_PARAM_M_PROTOCOLID) || !(rmMsg.dwParams & RIL_PARAM_M_COMMANDTYPE) ||
        !(rmMsg.dwParams & RIL_PARAM_M_TGTMSGREFERENCE) || !(rmMsg.dwParams & RIL_PARAM_M_CMDLENGTH) ||
        !(rmMsg.dwParams & RIL_PARAM_M_FLAGS)) {
        hr = E_INVALIDARG;
        goto Error;
    }

    // Set Type, per GSM 03.40 section 9.2.3.1
    *pbWalk |= 0x02;

    // See GSM 03.40 section 9.2.3.5
    if (rmMsg.dwFlags & RIL_MSGFLAG_STATUSREPORTREQUESTED) {
        *pbWalk |= 0x20;
    }
    // See GSM 03.40 section 9.2.3.23
    if (rmMsg.dwFlags & RIL_MSGFLAG_HEADER) {
        *pbWalk |= 0x40;
    }
    pbWalk++;
    TBD_ASSERT(pbWalk <= pbEnd);

    // Add a zero for the message reference (see GSM 03.40 section 9.2.3.6)
    // NOTE: it appears that we can put anything into this field -- the module generates correct msg reference for us
    pbWalk++;
    TBD_ASSERT(pbWalk <= pbEnd);

    // See GSM 03.40 section 9.2.3.9
    hr = EncodeMsgProtocolID(rmMsg.msgOutCommand.dwProtocolID, pbWalk, cbAdvancedBy);
    if (FAILED(hr)) {
        goto Error;
    }
    pbWalk += cbAdvancedBy;
    TBD_ASSERT(pbWalk <= pbEnd);

    // See GSM 03.40 section 9.2.3.19
    switch (rmMsg.msgOutCommand.dwCommandType)
    {
        case RIL_MSGCMDTYPE_STATUSREQ:
            *pbWalk++ = 0x00;
            break;

        case RIL_MSGCMDTYPE_CANCELSTATUSREQ:
            *pbWalk++ = 0x01;
            break;

        case RIL_MSGCMDTYPE_DELETEMESSAGE:
            *pbWalk++ = 0x02;
            break;

        case RIL_MSGCMDTYPE_ENABLESTATUSREQ:
            *pbWalk++ = 0x03;
            break;

        default:
            hr = E_INVALIDARG;
            goto Error;
    }
    TBD_ASSERT(pbWalk <= pbEnd);

    // See GSM 03.40 section 9.2.3.18
    if (0xff < rmMsg.msgOutCommand.dwTgtMsgReference) {
        hr = E_INVALIDARG;
        goto Error;
    }
    *pbWalk++ = (BYTE)rmMsg.msgOutCommand.dwTgtMsgReference;
    TBD_ASSERT(pbWalk <= pbEnd);

    // Encode the destination address.  pbMsg should be set properly by the function
    hr = EncodeMsgAddress(rmMsg.msgOutCommand.raDestAddress, FALSE, pbWalk, cbAdvancedBy);
    if (FAILED(hr)) {
        goto Error;
    }
    pbWalk += cbAdvancedBy;
    TBD_ASSERT(pbWalk <= pbEnd);

    // Encode command data length
    *pbWalk++ = (BYTE)rmMsg.msgOutCommand.cbCmdLength;
    TBD_ASSERT(pbWalk <= pbEnd);

    // Encode command data
    if (rmMsg.dwParams & RIL_PARAM_M_CMD) {
        cbAdvancedBy = min(rmMsg.msgOutCommand.cbCmdLength, MAXLENGTH_CMD);
        memcpy(pbWalk, rmMsg.msgOutCommand.rgbCmd, cbAdvancedBy);
        pbWalk += cbAdvancedBy;
    }
    rcbUsed = pbWalk - pbOut;

Error:
    return hr;
}


//
// Encode a Deliver message for SIM storage
//
static HRESULT EncodeDeliverMsg(const RILMESSAGE& rmMsg, BYTE* const pbOut, const UINT cbOut, UINT& rcbUsed)
{
    TBD_FUNCTION(EncodeDeliverMsg);
    TBD_ASSERT(NULL != pbOut);

    BYTE* pbWalk = pbOut;
    BYTE* pbEnd = pbOut + cbOut;
    UINT cbAdvancedBy;
    HRESULT hr = S_OK;

    (void)memset(pbOut, 0, cbOut);

    // These parameters are mandatory, and if not present, we error out.
    if (!(rmMsg.dwParams & RIL_PARAM_M_TYPE) || !(rmMsg.dwParams & RIL_PARAM_M_FLAGS) ||
        !(rmMsg.dwParams & RIL_PARAM_M_ORIGADDRESS) || !(rmMsg.dwParams & RIL_PARAM_M_PROTOCOLID) ||
        !(rmMsg.dwParams & RIL_PARAM_M_MSGLENGTH) || !(rmMsg.dwParams & RIL_PARAM_M_SCRECEIVETIME) ||
        !(rmMsg.dwParams & RIL_PARAM_M_DATACODING)) {
        hr = E_INVALIDARG;
        goto Error;
    }

    // Set Type, per GSM 03.40 section 9.2.3.1
    *pbWalk |= 0x00;

    // RIL_MSGFLAGS_MORETOSEND, GSM 03.40 section 9.2.3.2
    if (!(rmMsg.dwFlags & RIL_MSGFLAG_MORETOSEND)) {
        *pbWalk |= 0x04;
    }

    // RIL_MSGFLAG_STATUSREPORTRETURNED, GSM 03.40 section 9.2.3.4
    if (rmMsg.dwFlags & RIL_MSGFLAG_STATUSREPORTRETURNED) {
        *pbWalk |= 0x20;
    }

    // RIL_MSGFLAG_HEADER, GSM 03.40 section 9.2.3.23
    if (rmMsg.dwFlags & RIL_MSGFLAG_HEADER) {
        *pbWalk |= 0x40;
    }

    // RIL_MSGFLAG_REPLYPATH, GSM 03.40 section 9.2.3.17
    if (rmMsg.dwFlags & RIL_MSGFLAG_REPLYPATH) {
        *pbWalk |= 0x80;
    }
    pbWalk++;
    TBD_ASSERT(pbWalk <= pbEnd);

    // Encode the origination address
    hr = EncodeMsgAddress(rmMsg.msgInDeliver.raOrigAddress, FALSE, pbWalk, cbAdvancedBy);
    if (FAILED(hr)) {
        goto Error;
    }
    pbWalk += cbAdvancedBy;
    TBD_ASSERT(pbWalk <= pbEnd);

    // Set ProtocolID, see GSM 03.40 section 9.2.3.9
    hr = EncodeMsgProtocolID(rmMsg.msgInDeliver.dwProtocolID, pbWalk, cbAdvancedBy);
    if (FAILED(hr)) {
        goto Error;
    }
    pbWalk += cbAdvancedBy;
    TBD_ASSERT(pbWalk <= pbEnd);

    // Reconstruct DCS, see GSM 03.40 section 9.2.3.10
    hr = EncodeMsgDCS(rmMsg.msgInDeliver.rmdDataCoding, pbWalk, cbAdvancedBy);
    if (FAILED(hr)) {
        goto Error;
    }
    pbWalk += cbAdvancedBy;
    TBD_ASSERT(pbWalk <= pbEnd);

    // Encode receive timestamp
    if (rmMsg.dwParams & RIL_PARAM_M_SCRECEIVETIME) {
        EncodeMsgTimeStamp(rmMsg.msgInDeliver.stSCReceiveTime, pbWalk, cbAdvancedBy);
        pbWalk += cbAdvancedBy;
        TBD_ASSERT(pbWalk <= pbEnd);
    }

    // Encode header and body
    EncodeMsgHeaderAndBody(rmMsg.dwParams, rmMsg.dwFlags, rmMsg.msgInDeliver.cchMsgLength,
                           rmMsg.msgInDeliver.cbHdrLength, rmMsg.msgInDeliver.rgbHdr, rmMsg.msgInDeliver.rgbMsg,
                           &rmMsg.msgInDeliver.rmdDataCoding, pbWalk, cbAdvancedBy);
    pbWalk += cbAdvancedBy;
    TBD_ASSERT(pbWalk <= pbEnd);

    rcbUsed = pbWalk - pbOut;

Error:
    return hr;
}


//
// Encode a Status message for SIM storage
//
static HRESULT EncodeStatusMsg(const RILMESSAGE& rmMsg, BYTE* const pbOut, const UINT cbOut, UINT& rcbUsed)
{
    TBD_FUNCTION(EncodeStatusMsg);
    TBD_ASSERT(NULL != pbOut);

    BYTE* pbWalk = pbOut;
    BYTE* pbEnd = pbOut + cbOut;
    UINT cbAdvancedBy;
    HRESULT hr = S_OK;

    (void)memset(pbOut, 0, cbOut);

    // These parameters are mandatory, and if not present, we error out.
    if (!(rmMsg.dwParams & RIL_PARAM_M_TYPE) || !(rmMsg.dwParams & RIL_PARAM_M_FLAGS) ||
        !(rmMsg.dwParams & RIL_PARAM_M_TGTRECIPADDRESS) || !(rmMsg.dwParams & RIL_PARAM_M_TGTSCRECEIVETIME) ||
        !(rmMsg.dwParams & RIL_PARAM_M_TGTDISCHARGETIME) || !(rmMsg.dwParams & RIL_PARAM_M_TGTDLVSTATUS)) {
        hr = E_INVALIDARG;
        goto Error;
    }

    // Set Type, per GSM 03.40 section 9.2.3.1
    *pbWalk |= 0x02;

    // RIL_MSGFLAGS_MORETOSEND, GSM 03.40 section 9.2.3.2
    if (!(rmMsg.dwFlags & RIL_MSGFLAG_MORETOSEND)) {
        *pbWalk |= 0x04;
    }

    // RIL_MSGFLAG_CAUSEDBYCOMMAND, GSM 03.40 section 9.2.3.26
    if (rmMsg.dwFlags & RIL_MSGFLAG_CAUSEDBYCOMMAND) {
        *pbWalk |= 0x20;
    }

    // RIL_MSGFLAG_HEADER, GSM 03.40 section 9.2.3.23
    if (rmMsg.dwFlags & RIL_MSGFLAG_HEADER) {
        *pbWalk |= 0x40;
    }
    pbWalk++;
    TBD_ASSERT(pbWalk <= pbEnd);

    // Encode the Message Reference number
    if (0xff < rmMsg.msgInStatus.dwTgtMsgReference) {
        hr = E_INVALIDARG;
        goto Error;
    }
    *pbWalk++ = (BYTE)rmMsg.msgInStatus.dwTgtMsgReference;
    TBD_ASSERT(pbWalk <= pbEnd);

    // Encode the destination address.  pbMsg should be set properly by the function
    hr = EncodeMsgAddress(rmMsg.msgInStatus.raTgtRecipAddress, FALSE, pbWalk, cbAdvancedBy);
    if (FAILED(hr)) {
        goto Error;
    }
    pbWalk += cbAdvancedBy;
    TBD_ASSERT(pbWalk <= pbEnd);

    // Encode receive timestamp
    EncodeMsgTimeStamp(rmMsg.msgInStatus.stTgtSCReceiveTime, pbWalk, cbAdvancedBy);
    pbWalk += cbAdvancedBy;
    TBD_ASSERT(pbWalk <= pbEnd);

    // Encode discharge timestamp
    EncodeMsgTimeStamp(rmMsg.msgInStatus.stTgtDischargeTime, pbWalk, cbAdvancedBy);
    pbWalk += cbAdvancedBy;
    TBD_ASSERT(pbWalk <= pbEnd);

    // Encode devivery status
    hr = EncodeMsgDlvStatus(rmMsg.msgInStatus.dwTgtDlvStatus, pbWalk, cbAdvancedBy);
    if (FAILED(hr)) {
        goto Error;
    }
    pbWalk += cbAdvancedBy;
    TBD_ASSERT(pbWalk <= pbEnd);

    // Set the Parameter Indicator and encode the indicated fields
    // See GSM 03.40 section 9.2.3.27
    if (rmMsg.dwParams & RIL_PARAM_M_PROTOCOLID ||
        rmMsg.dwParams & RIL_PARAM_M_DATACODING ||
        rmMsg.dwParams & RIL_PARAM_M_MSGLENGTH) {
        *pbWalk = 0;
        if (rmMsg.dwParams & RIL_PARAM_M_PROTOCOLID) {
            *pbWalk |= 0x01;
        }
        if (rmMsg.dwParams & RIL_PARAM_M_DATACODING) {
            *pbWalk |= 0x20;
        }
        if (rmMsg.dwParams & RIL_PARAM_M_MSGLENGTH) {
            *pbWalk |= 0x40;
        }
        pbWalk++;
        TBD_ASSERT(pbWalk <= pbEnd);

        // Set ProtocolID if it exists.  see GSM 03.40 section 9.2.3.9
        if (rmMsg.dwParams & RIL_PARAM_M_PROTOCOLID) {
            hr = EncodeMsgProtocolID(rmMsg.msgInStatus.dwProtocolID, pbWalk, cbAdvancedBy);
            if (FAILED(hr)) {
                goto Error;
            }
            pbWalk += cbAdvancedBy;
            TBD_ASSERT(pbWalk <= pbEnd);
        }

        // Set DCS if it it exists.  see GSM 03.40 section 9.2.3.10
        if (rmMsg.dwParams & RIL_PARAM_M_DATACODING) {
            hr = EncodeMsgDCS(rmMsg.msgInStatus.rmdDataCoding, pbWalk, cbAdvancedBy);
            if (FAILED(hr)) {
                goto Error;
            }
            pbWalk += cbAdvancedBy;
            TBD_ASSERT(pbWalk <= pbEnd);
        }

        // Set Msg Data
        if (rmMsg.dwParams & RIL_PARAM_M_MSGLENGTH) {
            // Encode header and body
            EncodeMsgHeaderAndBody(rmMsg.dwParams, rmMsg.dwFlags, rmMsg.msgInStatus.cchMsgLength,
                                   rmMsg.msgInStatus.cbHdrLength, rmMsg.msgInStatus.rgbHdr, rmMsg.msgInStatus.rgbMsg,
                                   &rmMsg.msgInStatus.rmdDataCoding, pbWalk, cbAdvancedBy);
            pbWalk += cbAdvancedBy;
            TBD_ASSERT(pbWalk <= pbEnd);
        }
    }
    rcbUsed = pbWalk - pbOut;

Error:
    return hr;
}

//
// Fill out a BYTE array for a Raw message
//
static HRESULT EncodeRawMsg(const RILMESSAGE& rmMsg, BYTE* const pbOut, const UINT cbOut, UINT& rcbUsed)
{
    TBD_FUNCTION(EncodeRawMsg);
    HRESULT hr = S_OK;

    // These parameters are mandatory, and if not present, we error out.
    if (!(rmMsg.dwParams & RIL_PARAM_M_TYPE) || !(rmMsg.dwParams & RIL_PARAM_M_MSGLENGTH)) {
        hr = E_INVALIDARG;
        goto Error;
    }

    if (rmMsg.msgOutRaw.cchMsgLength > cbOut) {
        hr = E_FAIL;
        goto Error;
    }

    rcbUsed = min(cbOut, rmMsg.msgOutRaw.cchMsgLength);
    memcpy(pbOut, rmMsg.msgOutRaw.rgbMsg, rcbUsed);

Error:
    return hr;
}

//
// Encode an outgoing message from an RILMESSAGE to a BYTE array
//
HRESULT EncodeSMSMessage(const RILMESSAGE& rmMsg, const LPSTR sOut, const UINT cbOut, UINT& rcbUsed,
                         UINT& rnGSMLength)
{
    TBD_FUNCTION(EncodeSMSMessage);
    HRESULT hr = S_OK;
    BYTE rgbData[MAX_MSGBUFFER];
    UINT cbDataUsed;
    UINT cbAddress;

    // Encode the SMSC address
    if (rmMsg.dwParams & RIL_PARAM_M_SVCCTRADDRESS) {
        hr = EncodeMsgAddress(rmMsg.raSvcCtrAddress, TRUE, rgbData, cbAddress);
        if (FAILED(hr)) {
            goto Error;
        }
        TBD_ASSERT(MAX_MSGBUFFER >= cbAddress);
    } else {
        // SMSC address isn't specified -- indicate that by a 0 length byte
        *rgbData = 0;
        cbAddress = 1;
    }

    // Encode the rest of the
    switch (rmMsg.dwType)
    {
    case RIL_MSGTYPE_OUT_SUBMIT:
        hr = EncodeSubmitMsg(rmMsg, rgbData + cbAddress, MAX_MSGBUFFER - cbAddress, cbDataUsed);
        break;

    case RIL_MSGTYPE_OUT_COMMAND:
        hr = EncodeCmdMsg(rmMsg, rgbData + cbAddress, MAX_MSGBUFFER - cbAddress, cbDataUsed);
        break;

    case RIL_MSGTYPE_IN_DELIVER:
        hr = EncodeDeliverMsg(rmMsg, rgbData + cbAddress, MAX_MSGBUFFER - cbAddress, cbDataUsed);
        break;

    case RIL_MSGTYPE_IN_STATUS:
        hr = EncodeStatusMsg(rmMsg, rgbData + cbAddress, MAX_MSGBUFFER - cbAddress, cbDataUsed);
        break;

    case RIL_MSGTYPE_OUT_RAW:
        hr = EncodeRawMsg(rmMsg, rgbData + cbAddress, MAX_MSGBUFFER - cbAddress, cbDataUsed);
        break;

    default:
        hr = E_FAIL;
        goto Error;
    }

    // GSM length is the number of characters used for the message itself (not including the SMSC address upfront)
    rnGSMLength = cbDataUsed;

    // Convert the byte array into the GSMHex representation (2 chars per byte)
    if (!GSMToGSMHex((LPCSTR)rgbData, cbDataUsed + cbAddress, sOut, cbOut, rcbUsed)) {
        hr = E_FAIL;
        goto Error;
    }

Error:
    return hr;
}
